import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_rider/event/click_amount_event.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';

class TaskLayoutController {
  bool decimal;
  dynamic number;
  TaskLayoutController(double number, {this.decimal = false});

  TaskLayoutState? _state;
  void _attatch(TaskLayoutState state) {
    _state = state;
  }
  void _dettach() {
    _state = null;
  }
  void refresh() {
    _state?.refresh();
  }
}

class TaskLayout extends StatefulWidget {
  num initNumber;
  int max;
  int min;
  final editParentText;
  int newVal;
  TaskLayoutController controller;
  TaskLayout(
      {Key? key, this.initNumber = 0, this.min = 0, this.max = 1000, this.editParentText, this.newVal =0,required this.controller})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return TaskLayoutState();
  }


}

class TaskLayoutState extends State<TaskLayout> {
  final _textController = TextEditingController(text: "");
  late StreamSubscription _eventFn;

  @override
  void initState() {
    super.initState();
    _textController.text = "${widget.initNumber}";
    widget.controller.number = widget.initNumber;
    widget.controller._attatch(this);
    _eventFn = eventBus.on<ClickAmountEvent>().listen((event) {
      _textController.text = event.amount.toString();
    });
  }

  @override
  void dispose() {
    super.dispose();
    _eventFn.cancel();
    widget.controller._dettach();
  }

  void refresh() {
    setState(() {
      _textController.text = widget.controller.number.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    print("----${widget.controller.number.toString()}");
    return Container(
      height: 36.rpx,
      decoration: BoxDecoration(
        color: UIColor.color_input,
        borderRadius: BorderRadius.circular(8.rpx),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          UText.getBkButton("-", 18.rpx,
              color: UIColor.color_t1,
              bkColor: Colors.white,
              width: 24.rpx,
              height: 24.rpx,
              radius: 4.rpx, onPressed: () {
                FocusManager.instance.primaryFocus?.unfocus();
                if (widget.controller.number > 0) {
                  setState(() {
                    widget.controller.number -= 1;
                    _textController.text = widget.controller.number.toString();
                    _textController.selection =
                        TextSelection.fromPosition(TextPosition(offset: _textController.text.length));
                    widget.editParentText();// 调用父级组件方法
                  });
                }
              }),
          Container(
            width: 64.rpx,
            alignment: Alignment.centerRight,
            child: TextField(
              controller: _textController,
              style: UITextStyle.main_text,
              keyboardType: TextInputType.numberWithOptions(decimal: widget.controller.decimal),
              maxLength: widget.controller.decimal ? "${widget.max}".length + 2 : "${widget.max}".length,
              textAlign: TextAlign.center,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.transparent,
                  ),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.transparent,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Colors.transparent,
                  ),
                ),
                counterText: "",
                contentPadding: EdgeInsets.zero,
              ),
              //inputFormatters: [MaxNumberInputFormatter(min: widget.min, max: widget.max)],
              inputFormatters: [XNumberTextInputFormatter(maxIntegerLength: 5, maxDecimalLength: widget.controller.decimal ? 2 : 0, isAllowDecimal: widget.controller.decimal)],
              onChanged: (text) {
                //FocusManager.instance.primaryFocus?.unfocus();
                try {
                  widget.controller.number = num.parse(text);
                  widget.editParentText();// 调用父级组件方法
                } catch (e, st) {
                  Log.i("", e, st);
                  widget.controller.number = 0;
                }
              },
              onEditingComplete:() {
                FocusManager.instance.primaryFocus?.unfocus();
              }
            ),
          ),
          UText.getBkButton("+", 18.rpx,
              color: Colors.white,
              bkColor: UIColor.color_primary,
              width: 24.rpx,
              height: 24.rpx,
              radius: 4.rpx, onPressed: () {
                FocusManager.instance.primaryFocus?.unfocus();
                if (widget.controller.number < widget.max) {
                  setState(() {
                    widget.controller.number += 1;
                    _textController.text = widget.controller.number.toString();
                    _textController.selection =
                        TextSelection.fromPosition(TextPosition(offset: _textController.text.length));
                    widget.editParentText();// 调用父级组件方法
                  });
                }
              }),
        ],
      ),
    );
  }
}

class MaxNumberInputFormatter extends TextInputFormatter {
  int max;
  int min;

  MaxNumberInputFormatter({this.max = 1, this.min = 0});

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    var curNum = 0.0;
    try {
      curNum = double.parse(newValue.text);
      // ignore: empty_catches
    } catch (e) {}
    if (curNum > max) {
      curNum = max*1.0;
    }
    if (curNum < min) {
      curNum = min*1.0;
    }
    var text = "$curNum";
    return TextEditingValue(
        text: text, selection: TextSelection.fromPosition(TextPosition(offset: text.length)));
  }
}

class XNumberTextInputFormatter extends TextInputFormatter {
  int _maxIntegerLength;
  int _maxDecimalLength;
  bool _isAllowDecimal;

  /// [maxIntegerLength]限定整数的最大位数，为null时不限
  /// [maxDecimalLength]限定小数点的最大位数，为null时不限
  /// [isAllowDecimal]是否可以为小数，默认是可以为小数，也就是可以输入小数点
  XNumberTextInputFormatter(
      {int maxIntegerLength = 1, int maxDecimalLength = 0, bool isAllowDecimal = true})
      : _maxIntegerLength = maxIntegerLength,
        _maxDecimalLength = maxDecimalLength,
        _isAllowDecimal = isAllowDecimal;

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text.trim(); //去掉前后空格
    int selectionIndex = newValue.selection.end;
    if (_isAllowDecimal) {
      if (value == '.') {
        value = '0.';
        selectionIndex++;
      } else if (value != '' && _isToDoubleError(value)) {
        //不是double输入数据
        return _oldTextEditingValue(oldValue);
      }
      //包含小数点
      if (value.contains('.')) {
        int pointIndex = value.indexOf('.');
        String beforePoint = value.substring(0, pointIndex);
//      print('$beforePoint');
        String afterPoint = value.substring(pointIndex + 1, value.length);
//      print('$afterPoint');
        //小数点前面没内容补0
        if (beforePoint.isEmpty) {
          value = '0.${afterPoint}';
          selectionIndex++;
        } else {
          //限定整数位数
          if (null != _maxIntegerLength) {
            if (beforePoint.length > _maxIntegerLength) {
              return _oldTextEditingValue(oldValue);
            }
          }
        }
        //限定小数点位数
        if (null != _maxDecimalLength) {
          if (afterPoint.length > _maxDecimalLength) {
            return _oldTextEditingValue(oldValue);
          }
        }
      } else {
        //限定整数位数
        if (null != _maxIntegerLength) {
          if (value.length > _maxIntegerLength) {
            return _oldTextEditingValue(oldValue);
          }
        }
      }
    } else {
      if (value.contains('.') ||
          (value != '' && _isToDoubleError(value)) ||
          (null!=_maxIntegerLength&&value.length > _maxIntegerLength)) {
        return _oldTextEditingValue(oldValue);
      }
    }

    return TextEditingValue(
      text: value,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }

  ///返回旧的输入内容
  TextEditingValue _oldTextEditingValue(TextEditingValue oldValue) {
    return TextEditingValue(
      text: oldValue.text,
      selection: TextSelection.collapsed(offset: oldValue.selection.end),
    );
  }

  ///输入内容不能解析成double
  bool _isToDoubleError(String value) {
    try {
      double.parse(value);
    } catch (e) {
      return true;
    }
    return false;
  }
}